package com.xdl.flytest.controller;

import com.xdl.flytest.bean.Interface;
import com.xdl.flytest.bean.InterfaceInfo;
import com.xdl.flytest.bean.Project;
import com.xdl.flytest.service.InterfaceService;
import com.xdl.flytest.service.ProjectService;
import com.xdl.flytest.service.UserService;
import com.xdl.flytest.util.JsonResponseMessage;
import com.xdl.flytest.util.ResponseMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: 80736
 * @Date: 2018/12/28 17:58
 * @Description: 项目管理
 */
@Controller
@RequestMapping("/proj")
public class ProjectManagerController {

    private Logger logger = LoggerFactory.getLogger(ProjectManagerController.class);

    @Autowired
    private ProjectService projectService;

    @Autowired
    private UserService userService;

    @Autowired
    private InterfaceService interfaceService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 显示项目管理列表
     *
     * @return
     */
    @RequestMapping("/project_view")
    public ModelAndView projectIndex() {
        ModelAndView mav = new ModelAndView("project/page-project");
        List<Project> allProjects = projectService.getAllProjects();
        mav.addObject("projects", allProjects);
        return mav;
    }

    /**
     * 获取所有项目
     *
     * @return
     */
    @RequestMapping(value = "/projects", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getAllProject() {
        List<Project> allProjects = projectService.getAllProjects();
        return new JsonResponseMessage(ResponseMsg.SUCCESS).addAttribute("projects", allProjects).returned();
    }

    /**
     * 获取项目
     *
     * @param projectName
     * @return
     */
    @RequestMapping(value = "/project", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getProject(String projectName) {

        Project project = projectService.getProjectByName(projectName);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("msg", ResponseMsg.SUCCESS.getCode());
        map.put("project", project);

        return map;
    }

    /**
     * 新增项目
     * what the fuck !!!
     * public写成private导致一直url访问不到
     * 另外传入的参数类型和bean类型不一致也会导致报400错误
     *
     * @param project
     * @return
     */
    @RequestMapping(value = "/project", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addProject(@Validated Project project, BindingResult result, HttpSession session) {
        Map<String, Object> map = new LinkedHashMap<>();
        if (result.hasErrors()) {
            map.put("msg", ResponseMsg.PARAMETER_ERROR);
            map.put("error", result.getFieldError().getField());
            return map;
        }

        String userEmail = (String) session.getAttribute("email");
        project.setCreatorId(userService.getUserByEmail(userEmail).getUserId());
        map.put("msg", ResponseMsg.SUCCESS.getCode());
        projectService.addProject(project);
        return map;

    }

    /**
     * 更新项目
     *
     * @param project
     * @return
     */
    @RequestMapping(value = "/project", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> updateProject(Project project) {

        projectService.updateProject(project);
        logger.debug("**********更新项目信息成功**************");
        return ResponseMsg.result(ResponseMsg.SUCCESS);
    }

    /**
     * 删除项目
     *
     * @param projectId
     * @return
     */
    @RequestMapping(value = "/project", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> deleteProject(String projectId) {

        projectService.deleteProjectById(Integer.parseInt(projectId));
        return ResponseMsg.success();
    }


    @RequestMapping(value = "/interfaces", method = RequestMethod.GET)
    public ModelAndView getAllInterfaces() {
        ModelAndView mav = new ModelAndView();
        List<Interface> interfaces = interfaceService.getInterfaces();
        mav.addObject("interfaces", interfaces);
        mav.setViewName("project/page-interface");

        return mav;
    }

    @RequestMapping(value = "/interface", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getInterface(@RequestParam("interfaceId") String interfaceId) {

        if (interfaceId != null) {
            Interface in = interfaceService.getInterfaceById(Integer.parseInt(interfaceId));
            return new JsonResponseMessage(ResponseMsg.SUCCESS).addAttribute("interface", in).returned();
        }

        return new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR).returned();
    }

    @RequestMapping(value = "/interface/project", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getInterfaceByProject(@RequestParam("projectId") String projectId) {

        if (projectId != null) {
            List<Interface> interfaces = interfaceService.getInterfaceByProjectId(Integer.parseInt(projectId));
            return new JsonResponseMessage(ResponseMsg.SUCCESS).addAttribute("interfaces", interfaces).returned();
        }

        return new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR).returned();
    }

    /**
     * 新增接口
     *
     * @param ife
     * @param result
     * @return
     */
    @RequestMapping(value = "/interface", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addInterface(@Validated Interface ife, BindingResult result) {

        if (result.hasErrors()) {
            return new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR)
                    .addAttribute(result.getFieldError().getField(), result.getFieldError().getDefaultMessage())
                    .returned();
        }
//        String projectName = ife.getProject().getProjectName();
//        Integer projectId = projectService.getProjectByName(projectName).getProjectId();
//        ife.setBelongTo(projectId);
        interfaceService.addInterface(ife);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    /**
     * 更新接口
     *
     * @param in
     * @param result
     * @return
     */
    @RequestMapping(value = "/interface", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> updateInterface(@Validated Interface in, BindingResult result) {

        if (result.hasErrors()) {
            return new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR)
                    .addAttribute(result.getFieldError().getField(), result.getFieldError().getDefaultMessage())
                    .returned();
        }
        // 根据参数内修改的所属项目，查询项目的id
//        Integer newProjectId = projectService.getProjectByName(in.getProject().getProjectName()).getProjectId();
//        in.setBelongTo(newProjectId);
        interfaceService.updateInterface(in);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    /**
     * 根据id删除接口
     *
     * @param interfaceId
     * @return
     */
    @RequestMapping(value = "/interface", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> deleteInterface(@RequestParam("id") String interfaceId) {

        boolean result = interfaceService.deleteInterface(Integer.parseInt(interfaceId));
        if (result) {
            return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
        }
        return new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR).returned();
    }



}
